import { useEffect, useState } from 'react'
import { Form, Input, Button, TextArea, ImageUploader, Toast, Switch } from 'antd-mobile'
import { uploadFileToOSS } from '@utils/upload'
import { meetingSave } from '@api'
import { useNavigate, useParams } from 'react-router-dom'
import { getWatermark } from '@utils/index'
import './index.scss'

const MeetingAdd = () => {
    const navigate = useNavigate()
    const { meetingId } = useParams()

    const [fileList, setFileList] = useState([])

    const [showWatermark, setShowWatermark] = useState(false)

    const [form] = Form.useForm()

    useEffect(() => {
        if (meetingId) {
            const obj = JSON.parse(localStorage.getItem('meetingItem') || '{}')
            obj.imagesList = obj.imagesList.map((e) => ({ url: e }))
            form.setFieldsValue(obj)
        }
    }, [meetingId])

    // 上传
    const upload = async (file) => {
        const bool = form.getFieldValue('switch')
        const watermarkText = form.getFieldValue('watermark')
        let result = null;
        if(bool){
            result = await getWatermark(file, watermarkText)
        }
        const { res } = await uploadFileToOSS({ file: result || file })
        try {
            return { url: res.requestUrls[0].split('?')[0] }
        } catch (error) {
            throw new Error(error)
        }
    }

    const onFinish = (values) => {
        values.imagesList = values.imagesList.map((e) => e.url)
        meetingSave(values).then(({ success, info }) => {
            if (success) {
                Toast.show({
                    content: '操作成功~'
                })
                navigate('/meeting')
            } else {
                Toast.show({
                    content: info
                })
            }
        })
    }

    const onValuesChange = (obj) => {
        if (obj.switch === true || obj.switch === false) {
            setShowWatermark(obj.switch)
        }
    }

    return (
        <div className="MeetingAdd">
            <Form
                form={form}
                onFinish={onFinish}
                onValuesChange={onValuesChange}
                footer={
                    <Button block type="submit" color="primary" size="large">
                        提交
                    </Button>
                }
            >
                <Form.Item name="id" label="ID" style={{ display: 'none' }}>
                    <Input type="text" />
                </Form.Item>
                <Form.Item name="time" label="时间" rules={[{ required: true, message: '时间不能为空' }]}>
                    <Input type="date" placeholder="请选择时间" />
                </Form.Item>
                <Form.Item name="title" label="标题" rules={[{ required: true, message: '标题不能为空' }]}>
                    <Input placeholder="请输入标题" />
                </Form.Item>
                <Form.Item name="type" label="类型" rules={[{ required: true, message: '类型不能为空' }]}>
                    <Input placeholder="请输入类型" />
                </Form.Item>
                <Form.Item name="person" label="记录人员" rules={[{ required: true, message: '记录人员不能为空' }]}>
                    <Input placeholder="请输入记录人员" />
                </Form.Item>
                <Form.Item name="address" label="地址" rules={[{ required: true, message: '地址不能为空' }]}>
                    <Input placeholder="请输入地址" />
                </Form.Item>
                <Form.Item name="content" label="文案" rules={[{ required: true, message: '文案不能为空' }]}>
                    <TextArea placeholder="请输入文案" maxLength={1000} rows={6} showCount />
                </Form.Item>
                <Form.Item name="switch" label="是否加水印" childElementPosition="right">
                    <Switch />
                </Form.Item>
                {showWatermark ? (
                    <Form.Item name="watermark" label="水印文案" rules={[{ required: true, message: '水印文案不能为空' }]} help="'中' '左' '右' 使用 '/' 隔开">
                        <TextArea placeholder="请输入水印文案" />
                    </Form.Item>
                ) : null}

                <Form.Item name="imagesList" label="图片" rules={[{ required: true, message: '图片不能为空' }]}>
                    <ImageUploader
                        style={{ '--cell-size': '110px' }}
                        value={fileList}
                        multiple
                        upload={upload}
                        maxCount={9}
                        showUpload={fileList.length < 9}
                        onChange={setFileList}
                        onCountExceed={(exceed) => {
                            Toast.show(`最多选择 ${9} 张图片，你多选了 ${exceed} 张`)
                        }}
                    />
                </Form.Item>
            </Form>
        </div>
    )
}
export default MeetingAdd
